<template>
  <div class="metric-pie">
    <div class="metric-title">{{ title }}</div>
    <div class="pie-container">
      <!-- 蓝色方数据 -->
      <div class="team-data blue-side">

        <div class="player-bars">
          <div v-for="(player, index) in bluePlayers" :key="'blue'+index" class="player-bar">
            <div class="bar-container">
              <div><img
                    style="width:15px;
                            height: 15px;
                            color: transparent;"
                    loading="lazy"
                    decoding="async"
                    data-nimg="1"
                    class="rounded-[4px]"
                    :src="`https://opgg-static.akamaized.net/meta/images/lol/15.13.1/champion/${getChampionName(player)}.png?image=c_crop,h_103,w_103,x_9,y_9/q_auto:good,f_webp,w_160,h_160&amp;v=1513`"
                ></div>
              <div class="progress-bar">

                <div class="bar-fill"
                     :style="{
                       width: getPlayerWidth(player) + '%',
                       backgroundColor: 'rgb(83,131,232)'
                     }">
                  <span class="bar-value">{{ getPlayerValue(player) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 饼图 -->
      <div ref="chartDom" class="pie-chart"></div>

      <!-- 红色方数据 -->
      <div class="team-data red-side">

        <div class="player-bars">
          <div v-for="(player, index) in redPlayers" :key="'red'+index" class="player-bar">
            <div class="bar-container">
              <div><img
                  style="width:15px;
                            height: 15px;
                            color: transparent;"
                  loading="lazy"
                  decoding="async"
                  data-nimg="1"
                  class="rounded-[4px]"
                  :src="`https://opgg-static.akamaized.net/meta/images/lol/15.13.1/champion/${getChampionName(player)}.png?image=c_crop,h_103,w_103,x_9,y_9/q_auto:good,f_webp,w_160,h_160&amp;v=1513`"
              ></div>
              <div class="progress-bar">
                <div class="bar-fill"
                     :style="{
                       width: getPlayerWidth(player) + '%',
                       backgroundColor: 'rgb(232,64,87)'
                     }">
                  <span class="bar-value">{{ getPlayerValue(player) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  props: {
    title: String,
    blueValue: Number,
    redValue: Number,
    bluePlayers: Array,
    redPlayers: Array,
    format: Function,
    statKey: String // 新增：指定要显示的统计字段
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.initChart()
    window.addEventListener('resize', this.handleResize)
  },
  methods: {
    getChampionName(player) {
      return player.championName || '未知英雄';
    },
    getPlayerValue(player) {
      if (!this.statKey) return ''

      // 根据不同的统计字段获取值
      switch(this.statKey) {
        case 'kills':
          return player.kills
        case 'damageDealt':
          return this.formatDamage(player.totalDamageDealtToChampions)
        case 'damageTaken':
          return this.formatDamage(player.totalDamageTaken)
        case 'gold':
          return this.formatGold(player.goldEarned)
        case 'wards':
          return player.wardsPlaced
        case 'minions':
          return player.totalMinionsKilled
        default:
          return player[this.statKey] || ''
      }
    },

    getPlayerWidth(player) {
      if (!this.statKey) return 0

      // 获取当前队伍的所有玩家
      const teamPlayers = player.teamId === 100 ? this.bluePlayers : this.redPlayers

      // 获取当前统计字段的最大值
      const maxValue = Math.max(...teamPlayers.map(p => {
        switch(this.statKey) {
          case 'kills': return p.kills
          case 'damageDealt': return p.totalDamageDealtToChampions
          case 'damageTaken': return p.totalDamageTaken
          case 'gold': return p.goldEarned
          case 'wards': return p.wardsPlaced
          case 'minions': return p.totalMinionsKilled
          default: return p[this.statKey] || 0
        }
      }))

      if (maxValue === 0) return 0

      // 计算当前玩家的宽度百分比
      const playerValue = this.getPlayerRawValue(player)
      return (playerValue / maxValue) * 100
    },

    getPlayerRawValue(player) {
      if (!this.statKey) return 0

      switch(this.statKey) {
        case 'kills': return player.kills
        case 'damageDealt': return player.totalDamageDealtToChampions
        case 'damageTaken': return player.totalDamageTaken
        case 'gold': return player.goldEarned
        case 'wards': return player.wardsPlaced
        case 'minions': return player.totalMinionsKilled
        default: return player[this.statKey] || 0
      }
    },

    formatDamage(value) {
      return (value / 1000).toFixed(1) + 'k'
    },

    formatGold(value) {
      return (value / 1000).toFixed(1) + 'k'
    },

    initChart() {
      this.chart = echarts.init(this.$refs.chartDom)
      this.updateChart()
    },

    updateChart() {
      const total = this.blueValue + this.redValue;
      const bluePercent = total > 0 ? Math.round((this.blueValue / total) * 100) : 50;
      const redPercent = total > 0 ? Math.round((this.redValue / total) * 100) : 50;

      const option = {
        series: [{
          type: 'pie',
          radius: ['70%', '90%'],
          avoidLabelOverlap: false,
          silent: true,
          label: {
            show: true,
            position: 'center',
            formatter: [
              '{blue|' + this.blueValue + '}',
              '{divider|———}',
              '{red|' + this.redValue + '}'
            ].join('\n'),
            rich: {
              blue: {
                color: 'rgb(83,131,232)',
                fontSize: 12,
                fontWeight: 'bold',
                lineHeight: 10
              },
              red: {
                color: 'rgb(232,64,87)',
                fontSize: 12,
                fontWeight: 'bold',
                lineHeight: 10
              },
              divider: {
                color: '#666',
                fontSize: 10,
                lineHeight: 10,
                align: 'center',
                width: 30
              }
            }
          },
          labelLine: {
            show: false
          },
          data: [
            {
              value: this.blueValue,
              itemStyle: { color: 'rgb(83,131,232)' },
              emphasis: { scale: false }
            },
            {
              value: this.redValue,
              itemStyle: { color: 'rgb(232,64,87)' },
              emphasis: { scale: false }
            }
          ],
          animationDuration: 1000,
          animationEasing: 'cubicOut'
        }]
      };
      this.chart.setOption(option);
    },

    handleResize() {
      this.chart?.resize()
    }
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.handleResize)
    this.chart?.dispose()
  }
}
</script>

<style scoped>
.metric-pie{

}

.metric-title {
  color: #ecf0f1;
  text-align: center;
  font-weight: bold;
  font-size: 13px;
  margin-bottom: -5%;
}

.pie-container {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  justify-content: center;

}

.pie-chart {
  margin-top: 20px;
  width: 100px;
  height: 100px;
  flex-shrink: 0;
}

.team-data {
  display: flex;
  height: 100%;
  width: 100%;
  padding: 10px;

}

.blue-side {
  background: rgba(52, 152, 219, 0.0);
}

.red-side {
  background: rgba(231, 76, 60, 0.0);
}

.player-bars {
  width: 100%;
}

.player-bar {
  margin: 3px 0;
}

.bar-container {
  display: flex;
  flex-direction: row;
  width: 100%;
}

.bar-label {
  display: flex;
  justify-content: space-between;
  font-size: 5px;
  color: #ecf0f1;
  margin-bottom: 2px;
}

.player-name {
  font-weight: bold;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 60%;
}

.champion-name {
  color: #bdc3c7;
}

.progress-bar {
  height: 16px;
  width: 96px;
  background: rgba(255,255,255,0.1);
  overflow: hidden;
}

.bar-fill {
  height: 100%;
  position: relative;
  min-width: 20px;
  transition: width 0.3s ease;
}

.bar-value {
  position: absolute;
  right: 4px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 10px;
  color: white;
  text-shadow: 0 0 2px rgba(0,0,0,0.5);
}

.team-value {
  width: 100%;
  font-weight: bold;
  font-size: 18px;
  margin-bottom: 10px;
  text-align: center;
}

@media (max-width: 768px) {
  .pie-container {
    flex-direction: column;
  }

  .team-data {
    width: 100%;
    margin: 10px 0;
  }
}
</style>